package com.yanqu.road.utils.probability;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 概率抽取 通过概率分布数组, 每次随机一个索引
 */
public class ProbabilityItems<E> {
	/**
	 * 概率所在的比率分布
	 */
	private int[] rates;
	private int max = 0;
	private List<E> items;
	
	@FunctionalInterface
	public interface IProbabilityValue<E> {
		int getWeight(E item);
	}
	
	/**
	 * @param items 要抽取的对象列表
	 * @param weighter IProbabilityValue的getWeight方法,如果为null,表示权重全部为1
	 */
	public ProbabilityItems(List<E> items, IProbabilityValue<E> weighter) {
		this.items = items;
		this.rates = new int[items.size()];
		for (int i = 0; i < rates.length; i++) {
			this.rates[i] = max = max + (weighter == null?1:weighter.getWeight(items.get(i)));
		}
	}

	/**
	 * 获取下次抽中的索引
	 */
	public int nextIndex() {
		int ran = ThreadLocalRandom.current().nextInt(max);
		for (int i = 0; i < rates.length; i++) {
			if (ran < rates[i]) {
				return i;
			}
		}
		return 0;
	}
	
	public E nextItem() {
		return items.get(nextIndex());
	}

	public int getMax() {
		return max;
	}
	
	public int size() {
		return items.size();
	}
	
	public List<E> getList() {
		return items;
	}
}
